package com.kyh.util.jisu;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class JisuUtil {
	
	private static String APPKEY = "c1504f57b3c07c8f";
	private static String URL = "https://api.jisuapi.com/qrcode/read";
	
	public static void main(String[] args) {
		String urlpic = "http://fileaw.yijuran.com/upload/manage/2019/07/25/022727510.jpg";
		System.out.println(decode(urlpic));
	}
	
	/*
	 * {"status":0,"msg":"ok","result":"xxxxxxxx"}
	 */
	public static String decode(String urlpic) {
		String url = URL + "?qrcode=" + urlpic + "&appkey=" + APPKEY;
		String resultStr = sendGet(url);
		if (resultStr == null || resultStr.length() == 0) {
			return null;
		} else {
			JSONObject returnJO = JSON.parseObject(resultStr);
			int status = returnJO.getIntValue("status");
			if (status != 0) {
				return null;
			} else {
				String result = returnJO.getString("result");
				if ("false".equals(result)) {
					return null;
				} else {
					return result;
				}
			}
		}
	}

	/*
	 * url为包含参数的完整请求地址
	 */
	public static String sendGet(String url) {
		StringBuffer buffer = new StringBuffer();
		try {
			URL url_upcase = new URL(url);
			HttpURLConnection httpUrlConn = (HttpURLConnection) url_upcase.openConnection();

			httpUrlConn.setDoOutput(false);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);

			httpUrlConn.setRequestMethod("GET");
			httpUrlConn.connect();

			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();

		} catch (Exception e) {
			System.out.println(e.getStackTrace());
		}
		return buffer.toString();
	}
}
